package org.sword.wechat4j.message;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.sword.lang.HttpUtils;
import org.sword.wechat4j.event.MsgType;
import org.sword.wechat4j.exception.WeChatException;
import org.sword.wechat4j.token.TokenProxy;
import org.sword.wechat4j.util.WeChatUtil;

import com.alibaba.fastjson.JSONObject;

/**
 * 根据OpenID列表群发
 * @author wurenlong
 *
 */
public class MassCustomerMsg {

	Logger logger = Logger.getLogger(MassCustomerMsg.class);

	private static String optObj="<MassCustomerMsg>";
	
	private static final String OPENID_URL = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=";
	private static final String GROUP_URL = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=";
	private static final String PREVIEW_URL = "https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token=";
	
	private String[] toUserOpenIds;
	private String msgType;
	private String msgBody;
	private String msgId;
	private String msgDataId;
	
	/**
	 * [按openId群发]正式群发接口
	 */
	private String sendForOpenId(){
		String accessToken = TokenProxy.accessToken();
		if (StringUtils.isBlank(accessToken)) {
			logger.error("发送失败，无法得到accessToken");
			return null;
		}
		String url = OPENID_URL + accessToken;
		return HttpUtils.post(url, this.msgBody);
	}
	
	/**
	 * [按分组群发]正式群发接口
	 */
	private String sendForGroup(){
		String accessToken = TokenProxy.accessToken();
		if (StringUtils.isBlank(accessToken)) {
			logger.error("发送失败，无法得到accessToken");
			return null;
		}
		String url = GROUP_URL + accessToken;
		return HttpUtils.post(url, this.msgBody);
	}
	
	/**
	 * 预览接口
	 */
	private String previewSend() {
		String accessToken = TokenProxy.accessToken();
		if (StringUtils.isBlank(accessToken)) {
			logger.error("发送失败，无法得到accessToken");
			return null;
		}
		String url = PREVIEW_URL + accessToken;
		return HttpUtils.post(url, this.msgBody);
	}
	
	/**
	 * 群发图文消息预览
	 * @param mediaId
	 * @param toUserOpenIds
	 * @return boolean
	 */
	public boolean previewMpnews(String mediaId,String toUserOpenIds) {
		this.msgType = MsgType.mpnews.name();

		JSONObject jsonMsg = new JSONObject();
		jsonMsg.put("media_id", mediaId);
		
		JSONObject json = new JSONObject();
		json.put("msgtype", this.msgType);
		json.put("touser",  toUserOpenIds);
		json.put("mpnews", jsonMsg);

		this.msgBody = json.toJSONString();
		String result = this.previewSend();
		try {
			WeChatUtil.isSuccess(result);
			return true;
		} catch (WeChatException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 发送给所有用户 图文消息
	 * @param mediaId
	 * @return msgId
	 */
	public String sendMpnewsToAllUser(String mediaId){
		this.msgType = MsgType.mpnews.name();
		
		JSONObject mpnews = new JSONObject();
		mpnews.put("media_id", mediaId);
		
		JSONObject filter = new JSONObject();
		filter.put("is_to_all", true);
		
		JSONObject json = new JSONObject();
		json.put("msgtype", this.msgType);
		json.put("filter",  filter);
		json.put("mpnews", mpnews);
		
		this.msgBody = json.toJSONString();
		String result = this.sendForGroup();
		this.parseResult(result);
		if(StringUtils.isNotBlank(this.msgId)){
			return this.msgId;
		}
		return null;
	}

	/**
	 * 根据openId群发图文消息
	 * @param mediaId
	 * @param toUserOpenIds
	 * @return msgId
	 */
	public String sendMpnewsToOpenId(String mediaId,String[] toUserOpenIds) {
		this.toUserOpenIds = toUserOpenIds;
		this.msgType = MsgType.mpnews.name();

		JSONObject jsonMsg = new JSONObject();
		jsonMsg.put("media_id", mediaId);
		
		JSONObject json = new JSONObject();
		json.put("msgtype", this.msgType);
		json.put("touser",  this.toUserOpenIds);
		json.put("mpnews", jsonMsg);

		this.msgBody = json.toJSONString();
		String result = this.sendForOpenId();
		this.parseResult(result);
		if(StringUtils.isNotBlank(this.msgId)){
			return this.msgId;
		}
		return null;
	}
	
	/**
	 * 分析返回结果
	 * @param result
	 */
	private void parseResult(String result) {
		try {
			WeChatUtil.isSuccess(result);
			JSONObject jsonObject = JSONObject.parseObject(result);
			this.msgId = jsonObject.getString("msg_id");
			this.msgDataId = jsonObject.getString("msg_data_id");
		} catch (WeChatException e) {
			this.msgId = null;
			this.msgDataId = null;
			e.printStackTrace();
		}
	}

	public String[] getToUserOpenIds() {
		return toUserOpenIds;
	}

	public String getMsgType() {
		return msgType;
	}

	public String getMsgBody() {
		return msgBody;
	}

	public String getMsgId() {
		return msgId;
	}

	public String getMsgDataId() {
		return msgDataId;
	}
}
